package com.example.note.model.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 */
@Slf4j
public class SecurityUtils {
    /**
     * 加密
     * password 明文密码
     * 返回  盐值+密文
     */
    public static String encry(String password){
        //首先生成随机盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        System.out.println(salt);
        //加密为密文   对（盐值+明文）加密
        String securityPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        return  salt+securityPassword;
    }

    /**
     * 校验
     */
    public static boolean verify(String inputPassword,String sqlPassword){
        if(sqlPassword == null || sqlPassword.length()!=64){
            return  false;
        }
        //根据密文规则，取出盐值
        String salt = sqlPassword.substring(0,32);
        //得到密文
        String securityPassword = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes());
        //数据库中存储的是盐值+密文
        log.info((salt+securityPassword));
        log.info((sqlPassword));
        log.info("3456789");
        return (salt+securityPassword).equals(sqlPassword);
    }

    public static void main(String[] args) {
        String finalPassword = encry("123456");
        System.out.println(finalPassword);
        System.out.println(verify("123456",finalPassword));
    }
}
